﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Query;
using Happy.Query.Filters;

namespace Happy.Application.Query
{
    /// <summary>
    /// 查询请求。
    /// </summary>
    public sealed class QueryRequest
    {
        /// <summary>
        /// 显式的列。
        /// </summary>
        public List<string> Columns { get; set; }

        /// <summary>
        /// 查询参数。
        /// </summary>
        public SearchArgument[] Arguments { get; set; }

        /// <summary>
        /// 高级查询。
        /// </summary>
        public DynamicFilterGroup Group { get; set; }

        /// <summary>
        /// 排序器。
        /// </summary>
        public Sorter[] Sorters { get; set; }

        /// <summary>
        /// 页码。
        /// </summary>
        public long Page { get; set; }

        /// <summary>
        /// 每页显式的记录数。
        /// </summary>
        public long ItemsPerPage { get; set; }

        internal QueryArgument ToQueryArgument(FilterDefinition filterDefinition)
        {
            var queryArgument = new QueryArgument();

            queryArgument.Columns = this.Columns;

            if (this.Sorters != null)
            {
                queryArgument.OrderClauses = this.Sorters.ToOrderClauses();
            }

            var whereClauses = new List<WhereClause>();
            if (this.Group != null)
            {
                whereClauses.Add(this.Group.ToWhereClause());
            }
            if (filterDefinition != null)
            {
                whereClauses.Add(filterDefinition.BuildWhereClause(this.Arguments.ToArguments()));
            }
            queryArgument.WhereClauses = whereClauses;

            return queryArgument;
        }
    }
}
